import { View, Text } from "react-native";
import globalMethods from "@/GlobalMethodProvider";
import fso from "@/utils/FileOperate/operate";
import sm from "@/utils/ScheduleManage/operate";
import { destroy as websocketDestroy, setWsConnect } from "@/utils/websocket/index";
import { getDeviceInfoByCode } from "@/api/home";
import store from "@/store";
import navigation from "@/utils/navigation";

import type { DeviceType } from "@/typings/businessType";

const FILE_PATH = `${fso.baseDir}/ENTRY_NETWORK_INFO.json`;

/** 获取本地入网审核信息 */
export const getEntryNetworkInfo = (): Promise<DeviceType | null> => {
  return new Promise(async resolve => {
    try {
      // @ts-ignore
      let ret: DeviceType = {};
      const exists = await fso.exists(FILE_PATH);
      if (exists) {
        const res = await fso.readFile(FILE_PATH);
        ret = JSON.parse(res);
        resolve(ret);
      } else {
        resolve(null);
      }
    } catch (error) {
      fso.error("本地入网数据获取失败: ", error);
      resolve(null);
    }
  });
};

/** 设置入网审核信息 */
export const setEntryNetworkInfo = (val: DeviceType) => {
  return new Promise<boolean>(async resolve => {
    try {
      fso.info("本地存储入网信息: ", val);
      await fso.writeFile(FILE_PATH, JSON.stringify(val, null, 2));
      resolve(true);
    } catch (error) {
      fso.error("入网数据保存到本地失败: ", error);
      resolve(false);
    }
  });
};

/** 后台根据设备编号获取设备信息 */
export const fetchEntryNetworkInfo = async (text: string, isTip = false) => {
  try {
    fso.info("设置设备的编号: ", text);
    // 这里要使用设备编号进行查询
    const res = await getDeviceInfoByCode(text);
    const data: DeviceType | undefined = res.data;
    fso.info("查询的设备数据: ", data);
    if (data) {
      if (data.code === store.getState().index.entryNetworkInfo?.code) {
        globalMethods.$showMessage({
          message: `获取设备的编号跟当前设备的一致【${data.code}】`,
          type: 'toast',
        })
        return;
      }

      if (isTip) {
        // 提示设备的信息, 并确认
        const { confirm } = await globalMethods.$showModalBox({
          title: "请检查设备的信息",
          contentPosition: "center",
          contentComponent() {
            return (
              <View>
                <Text>设备名称: {data.name}</Text>
                <Text>设备编号: {data.code}</Text>
                <Text>所属机构: {data.officeName}</Text>
                <Text>设备厂家: {data.factory}</Text>
                <Text>区域: {data.area}</Text>
                <Text>规格型号: {data.model}</Text>
                <Text>设备分辨率: {data.resolutionRatio}</Text>
              </View>
            );
          }
        });
        if (!confirm) return;
      }

      // 取消下载任务
      if (sm.downloadingTaskData.length) sm.cancelDownMaterial();
      // 保存到本地
      await setEntryNetworkInfo(data);
      if (store.getState().index.isWebsocketConnect) {
        // 销毁websocket, 会导致连接关闭
        websocketDestroy();
        setWsConnect(false);
      }
      // 重新跳转到首页
      navigation.replace("Home");
    } else {
      const msg = `【${text}】没有查询到设备信息`;
      globalMethods.$showMessage({
        type: "toast",
        message: msg
      });
    }
  } catch (err) {
    console.log("err: ", err);
    fso.error("设备信息获取失败: ", text);
  }
};
